package com.kulian.Signalling.system.service.impl.socket.handler;

import com.kulian.Signalling.system.mode.socket.SignalingMessage;
import com.kulian.Signalling.system.service.impl.socket.MessageSender;
import com.kulian.Signalling.system.service.impl.socket.RoomManager;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
@RequiredArgsConstructor
public class CallMessageHandler {
    private final MessageSender messageSender;
    private final RoomManager roomManager;
    
    // Track active calls: key=caller, value=callee
    private final Map<String, String> activeCalls = new ConcurrentHashMap<>();

    public void handleCallRequest(String from, String to, String roomId) {
        if (!roomManager.isUserOnline(to)) {
            messageSender.sendError(from, "用户不在线");
            return;
        }
        
        SignalingMessage message = createBaseMessage(from, to, roomId);
        message.setType(SignalingMessage.MessageType.CALL_REQUEST.name());
        activeCalls.put(from, to);
        
        messageSender.sendToUser(to, message);
    }

    public void handleCallAccept(String from, String to, String roomId) {
        SignalingMessage message = createBaseMessage(from, to, roomId);
        message.setType(SignalingMessage.MessageType.CALL_ACCEPT.name());
        messageSender.sendToUser(to, message);
    }

    public void handleCallReject(String from, String to) {
        SignalingMessage message = createBaseMessage(from, to, null);
        message.setType(SignalingMessage.MessageType.CALL_REJECT.name());
        messageSender.sendToUser(to, message);
        activeCalls.remove(from);
    }

    public void handleRinging(String from, String to) {
        SignalingMessage message = createBaseMessage(from, to, null);
        message.setType(SignalingMessage.MessageType.RINGING.name());
        messageSender.sendToUser(to, message);
    }

    public void handleHangup(String from, String to, String roomId) {
        SignalingMessage message = createBaseMessage(from, to, roomId);
        message.setType(SignalingMessage.MessageType.HANGUP.name());
        messageSender.sendToUser(to, message);
        activeCalls.remove(from);
    }

    private SignalingMessage createBaseMessage(String from, String to, String roomId) {
        SignalingMessage message = new SignalingMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setRoomId(roomId);
        message.setTimestamp(System.currentTimeMillis());
        return message;
    }
}
